<template>
  <a-drawer
    v-model:open="visible"
    :title="isEdit ? '编辑配置' : '新增配置'"
    width="1200"
    placement="right"
    @close="handleClose"
  >
    <!-- 基本信息表单 -->
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      class="mt-4 mb-6"
    >
      <a-form-item label="服务商ID" name="providerId">
        <a-select
          v-model:value="formData.providerId"
          placeholder="请选择服务商"
        >
          <a-select-option v-for="provider in getAllProviders()" :key="provider.id" :value="provider.id">
            {{ provider.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="渠道ID" name="channelId">
        <a-select
          v-model:value="formData.channelId"
          placeholder="请选择渠道"
          @change="handleChannelChange"
        >
          <a-select-option v-for="channel in getAllChannels()" :key="channel.id" :value="channel.id">
            {{ channel.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="环境" name="isSandbox">
        <a-radio-group v-model:value="formData.isSandbox">
          <a-radio :value="1">沙箱环境</a-radio>
          <a-radio :value="0">生产环境</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="状态" name="status">
        <a-switch
          v-model:checked="statusChecked"
          checked-children="启用"
          un-checked-children="禁用"
        />
      </a-form-item>
    </a-form>

    <!-- Tab配置区域 -->
    <template v-if="currentChannelTemplate">
      <a-tabs class="config-tabs">
        <a-tab-pane key="base" tab="基础配置">
          <div class="text-gray-500 text-sm mb-4">
            <i class="text-blue-500">提示：</i> 以下配置项均为可选，可根据实际需要填写，最终以JSON格式存储
          </div>
          <a-form
            ref="baseConfigFormRef"
            :model="formData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-form-item
              v-for="item in generateBaseConfigForm()"
              :key="item.key"
              :label="item.schema.label"
            >
              <a-input
                v-if="item.schema.type === 'string'"
                :value="getBaseConfigValue(item.key)"
                @update:value="(val: string) => updateBaseConfig(item.key, val)"
                :placeholder="`请输入${item.schema.label}`"
              />
              <a-input-number
                v-else-if="item.schema.type === 'number'"
                :value="getBaseConfigValue(item.key)"
                @update:value="(val: number) => updateBaseConfig(item.key, val)"
                :placeholder="`请输入${item.schema.label}`"
                :min="item.schema.validation?.min"
                :max="item.schema.validation?.max"
                class="w-full"
              />
              <a-switch
                v-else-if="item.schema.type === 'boolean'"
                :checked="getBaseConfigValue(item.key)"
                @update:checked="(val: boolean) => updateBaseConfig(item.key, val)"
              />
              <FileUpload
                v-else-if="item.schema.type === 'file'"
                :model-value="getBaseConfigValue(item.key) || ''"
                @update:model-value="(val) => updateBaseConfig(item.key, val)"
                :accept="'.p12,.pem,.crt,.cer'"
                :allowed-types="['.p12', '.pem', '.crt', '.cer']"
                :max-size="10"
                button-text="选择证书文件"
              />
              <div v-if="item.schema.description" class="text-gray-500 text-sm mt-1">
                {{ item.schema.description }}
              </div>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="fee" tab="费率配置">
          <div class="text-gray-500 text-sm mb-4">
            <i class="text-blue-500">提示：</i> 费率配置为可选项，可根据渠道特点设置相应的费率参数
          </div>
          <a-form
            ref="feeConfigFormRef"
            :model="formData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-form-item
              v-for="item in generateFeeConfigForm()"
              :key="item.key"
              :label="item.schema.label"
            >
              <a-input
                v-if="item.schema.type === 'string'"
                :value="getFeeConfigValue(item.key)"
                @update:value="(val: string) => updateFeeConfig(item.key, val)"
                :placeholder="`请输入${item.schema.label}`"
              />
              <a-input-number
                v-else-if="item.schema.type === 'number'"
                :value="getFeeConfigValue(item.key)"
                @update:value="(val: number) => updateFeeConfig(item.key, val)"
                :placeholder="`请输入${item.schema.label}`"
                :min="item.schema.validation?.min"
                :max="item.schema.validation?.max"
                class="w-full"
              />
              <a-switch
                v-else-if="item.schema.type === 'boolean'"
                :checked="getFeeConfigValue(item.key)"
                @update:checked="(val: boolean) => updateFeeConfig(item.key, val)"
              />
              <div v-if="item.schema.description" class="text-gray-500 text-sm mt-1">
                {{ item.schema.description }}
              </div>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="ext" tab="扩展配置">
          <a-form
            ref="extConfigFormRef"
            :model="formData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-form-item label="扩展配置" name="extraConfig">
              <a-textarea
                v-model:value="formData.extraConfig"
                :rows="12"
                placeholder="请输入扩展配置（JSON格式）"
              />
              <div class="text-gray-500 text-sm mt-1">
                请输入有效的JSON格式配置，用于存储渠道的自定义扩展信息
              </div>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </template>

    <!-- 操作按钮 -->
    <div class="flex justify-end gap-2 mt-6 pt-4 border-t">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? '保存' : '创建' }}
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { getChannelTemplate } from './channel-templates';
import type { ProviderChannelConfig } from './types';
import FileUpload from '@/components/FileUpload.vue';
import { getAllChannels } from '@/constants/channels';
import { getAllProviders } from '@/constants/providers';

interface Props {
  visible: boolean;
  configData: ProviderChannelConfig | null;
  isEdit: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'submit', data: ProviderChannelConfig): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<FormInstance>();
const baseConfigFormRef = ref<FormInstance>();
const feeConfigFormRef = ref<FormInstance>();
const extConfigFormRef = ref<FormInstance>();

// 表单数据
const formData = ref<Partial<ProviderChannelConfig>>({
  providerId: undefined,
  channelId: undefined,
  isSandbox: 1,
  baseConfig: '{}',
  feeConfig: '{}',
  extraConfig: JSON.stringify({ remark: '请填写配置说明' }, null, 2),
  status: 1
});

// 内部配置对象
const baseConfigObj = ref<Record<string, any>>({});
const feeConfigObj = ref<Record<string, any>>({});

// 提交状态
const submitting = ref(false);

// 状态开关
const statusChecked = computed({
  get: () => formData.value.status === 1,
  set: (value) => formData.value.status = value ? 1 : 0
});

// 表单验证规则
const rules = {
  providerId: [
    { required: true, message: '请输入服务商ID', type: 'number' }
  ],
  channelId: [
    { required: true, message: '请选择渠道ID' }
  ],
  isSandbox: [
    { required: true, message: '请选择环境类型' }
  ]
};

// 根据渠道获取配置模板
const currentChannelTemplate = computed(() => {
  if (!formData.value.channelId) return null;

  const channelMap: Record<number, string> = {
    1: 'WECHAT',
    2: 'ALIPAY',
    3: 'LESHUA',
    4: 'DOUGONG'
  };

  const channelCode = channelMap[formData.value.channelId];
  return channelCode ? getChannelTemplate(channelCode) : null;
});

// 生成基础配置表单项
const generateBaseConfigForm = () => {
  if (!currentChannelTemplate.value) return [];

  return Object.entries(currentChannelTemplate.value.baseConfigSchema).map(([key, schema]) => ({
    key,
    schema
  }));
};

// 生成费率配置表单项
const generateFeeConfigForm = () => {
  if (!currentChannelTemplate.value) return [];

  return Object.entries(currentChannelTemplate.value.feeConfigSchema).map(([key, schema]) => ({
    key,
    schema
  }));
};

// 获取基础配置值
const getBaseConfigValue = (key: string) => {
  return baseConfigObj.value[key];
};

// 更新基础配置
const updateBaseConfig = (key: string, value: any) => {
  baseConfigObj.value[key] = value;
  formData.value.baseConfig = JSON.stringify(baseConfigObj.value);
};

// 获取费率配置值
const getFeeConfigValue = (key: string) => {
  return feeConfigObj.value[key];
};

// 更新费率配置
const updateFeeConfig = (key: string, value: any) => {
  feeConfigObj.value[key] = value;
  formData.value.feeConfig = JSON.stringify(feeConfigObj.value);
};

// 渠道改变处理
const handleChannelChange = () => {
  // 清空配置
  baseConfigObj.value = {};
  feeConfigObj.value = {};
  formData.value.baseConfig = '{}';
  formData.value.feeConfig = '{}';

  // 设置默认值
  if (currentChannelTemplate.value) {
    // 设置基础配置默认值
    Object.entries(currentChannelTemplate.value.baseConfigSchema).forEach(([key, schema]) => {
      if (schema.defaultValue !== undefined) {
        baseConfigObj.value[key] = schema.defaultValue;
      }
    });

    // 设置费率配置默认值
    Object.entries(currentChannelTemplate.value.feeConfigSchema).forEach(([key, schema]) => {
      if (schema.defaultValue !== undefined) {
        feeConfigObj.value[key] = schema.defaultValue;
      }
    });

    formData.value.baseConfig = JSON.stringify(baseConfigObj.value);
    formData.value.feeConfig = JSON.stringify(feeConfigObj.value);
  }
};

// 监听visible变化
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 监听配置数据变化
watch(() => props.configData, (newData) => {
  if (newData && props.visible) {
    formData.value = { ...newData };

    // 解析JSON配置
    try {
      // 确保 baseConfig 和 feeConfig 是字符串格式
      const baseConfigStr = typeof newData.baseConfig === 'string'
        ? newData.baseConfig
        : JSON.stringify(newData.baseConfig || {});
      const feeConfigStr = typeof newData.feeConfig === 'string'
        ? newData.feeConfig
        : JSON.stringify(newData.feeConfig || {});

      baseConfigObj.value = JSON.parse(baseConfigStr);
      feeConfigObj.value = JSON.parse(feeConfigStr);

      // 更新表单数据中的JSON字符串
      formData.value.baseConfig = baseConfigStr;
      formData.value.feeConfig = feeConfigStr;
    } catch (error) {
      console.error('解析配置JSON失败:', error);
      baseConfigObj.value = {};
      feeConfigObj.value = {};
      formData.value.baseConfig = '{}';
      formData.value.feeConfig = '{}';
    }
  }
}, { immediate: true });

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    // 验证JSON格式
    try {
      if (formData.value.extraConfig) {
        JSON.parse(formData.value.extraConfig);
      }
    } catch {
      message.error('扩展配置JSON格式错误');
      return;
    }

    submitting.value = true;

    const submitData = {
      ...formData.value,
      baseConfig: formData.value.baseConfig || '{}',
      feeConfig: formData.value.feeConfig || '{}',
      extraConfig: formData.value.extraConfig || '{}'
    } as ProviderChannelConfig;

    emit('submit', submitData);

  } catch (error) {
    message.error('请检查表单填写');
  } finally {
    submitting.value = false;
  }
};

// 处理取消
const handleCancel = () => {
  handleClose();
};

// 处理关闭
const handleClose = () => {
  // 先重置内部数据对象
  baseConfigObj.value = {};
  feeConfigObj.value = {};

  // 重置表单数据为初始状态
  resetForm();

  // 只重置主表单的验证状态
  formRef.value?.resetFields();

  emit('update:visible', false);
  emit('close');
};

// 重置表单数据
const resetForm = () => {
  formData.value = {
    providerId: undefined,
    channelId: undefined,
    isSandbox: 1,
    baseConfig: '{}',
    feeConfig: '{}',
    extraConfig: JSON.stringify({ remark: '请填写配置说明' }, null, 2),
    status: 1
  };
  baseConfigObj.value = {};
  feeConfigObj.value = {};
};

// 监听visible变化，重置表单
watch(() => props.visible, (visible) => {
  if (visible && !props.isEdit) {
    resetForm();
  }
});
</script>

<style scoped>
.config-tabs :deep(.ant-tabs-content-holder) {
  padding: 16px 0;
}

.config-tabs :deep(.ant-tabs-tab) {
  padding: 12px 16px;
}

.config-tabs :deep(.ant-form-item) {
  margin-bottom: 20px;
}

.config-tabs :deep(.ant-form-item-label) {
  font-weight: 500;
}

.config-tabs :deep(.ant-input-number) {
  width: 100%;
}

.config-tabs .text-gray-500 {
  font-size: 12px;
  line-height: 1.4;
  margin-top: 4px;
}

.text-blue-500 {
  color: #3b82f6;
}

.border-t {
  border-top: 1px solid #e5e7eb;
}

.gap-2 {
  gap: 8px;
}

.w-full {
  width: 100%;
}
</style>